package admin

// by daoyi
import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"math/rand"
	"simai_oa/controller"
	"simai_oa/model"
	"simai_oa/tool"
)

type Admins struct{}

// List
//
//	@Summary	分页数据
//	@Tags		后台-管理员
//	@param		page	query		int		false	"多少页"
//	@param		limit	query		int		false	"每页多少条"
//	@param		sort	query		string	false	"排序"
//	@param		role_id	query		int		false	"角色id"
//	@param		key		query		string	false	"搜索条件"
//	@param		status	query		string	false	"状态(1:正常 2:禁用)"
//	@Success	200		{string}	json{"code","message","data"}
//	@Router		/admin/admins/list [GET]
func (Admins) List(c *gin.Context) {
	page := controller.GetPageIndex(c)
	limit := controller.GetPageLimit(c)
	sort := controller.GetPageSort(c)
	key := controller.GetPageKey(c)
	status := controller.GetQueryToUint(c, "status")
	role_id := controller.GetQueryToUint(c, "role_id")
	var whereOrder []model.PageWhereOrder
	order := "ID DESC"
	if len(sort) >= 2 {
		orderType := sort[0:1]
		order = sort[1:len(sort)]
		if orderType == "+" {
			order += " ASC"
		} else {
			order += " DESC"
		}
	}
	whereOrder = append(whereOrder, model.PageWhereOrder{Order: order})
	if key != "" {
		v := "%" + key + "%"
		var arr []interface{}
		arr = append(arr, v)
		arr = append(arr, v)
		whereOrder = append(whereOrder, model.PageWhereOrder{Where: "name like ? or role_name like ?", Value: arr})
	}
	if status > 0 {
		var arr []interface{}
		arr = append(arr, status)
		whereOrder = append(whereOrder, model.PageWhereOrder{Where: "switch = ?", Value: arr})
	}
	if role_id > 0 {
		var arr []interface{}
		arr = append(arr, role_id)
		whereOrder = append(whereOrder, model.PageWhereOrder{Where: "role_id = ?", Value: arr})
	}
	var total int64
	list := []model.Admin{}
	err := model.GetPage(&model.Admin{}, &model.Admin{}, &list, page, limit, &total, whereOrder...)
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	controller.ResSuccessPage(c, total, &list)
}

// Detail
//
//	@Summary	详情
//	@Tags		后台-管理员
//	@param		id	query		int	false	"管理员id"
//	@Success	200	{string}	json{"code","message","data"}
//	@Router		/admin/admins/detail [GET]
func (Admins) Detail(c *gin.Context) {
	id := controller.GetQueryToInt(c, "id")
	var models model.Admin
	where := model.Admin{}
	where.Id = id
	_, err := model.First(&where, &models)
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	models.Pwd = ""
	controller.ResSuccess(c, &models)
}

// ResetPwd
//
//	@Summary	重置用户密码  使用headers头： Content-Type:application/json   使用raw json方式发送请求体
//	@Tags		后台-管理员
//	@Produce	json
//	@param		id			query		int	false	"id"
//	@Success	200			{string}	json{"code","message"}
//	@Router		/admin/admins/resetPwd [POST]
func (Admins) ResetPwd(c *gin.Context) {
	type Admin struct {
		Id int `json:"id" form:"id"`
	}
	models := Admin{}
	err := c.Bind(&models)
	fmt.Println(models)
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	where := model.Admin{}
	where.Id = models.Id
	modelOld := model.Admin{}
	_, err = model.First(&where, &modelOld)
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}

	kw := "_KW"
	pwd := tool.Md5string("123456" + kw)
	salt := fmt.Sprintf("%06d", rand.Int31())
	password := tool.Md5string(pwd + salt)

	err = tool.Gdb.Table("za_admin").Where("id = ?", models.Id).Updates(map[string]any{"pwd": password, "salt": salt}).Error
	if err != nil {
		log.Println(err)
		controller.ResFail(c, "操作失败")
		return
	}
	model.AdminLog(1, "重置密码,用户:"+modelOld.Name, c)
	controller.ResSuccessMsg(c)
}

// Update
//
//	@Summary	更新  使用headers头： Content-Type:application/json   使用raw json方式发送请求体
//	@Tags		后台-管理员
//	@Produce	json
//	@param		id			query		int	false	"id"
//	@param		real_name	query		int	false	"用户真实名称"
//	@param		tel			query		int	false	"联系方式"
//	@param		switch		query		int	false	"账号开关 2:关闭 1:开启"
//	@param		type		query		int	false	"管理员类型 1 部门主管 2普通员工"
//	@Success	200			{string}	json{"code","message"}
//	@Router		/admin/admins/update [POST]
func (Admins) Update(c *gin.Context) {
	type Data struct {
		Id       int    `json:"id" form:"id"`
		RealName string `json:"real_name" form:"real_name"`
		Tel      string `json:"tel" form:"tel"`
		Switch   int    `json:"switch" form:"switch"`
		Type     int    `json:"type" form:"type"`
	}
	models := Data{}
	err := c.Bind(&models)
	if err != nil {
		controller.ResErrSrv(c, err)
		return
	}
	where := model.Admin{}
	where.Id = models.Id
	modelOld := model.Admin{}
	_, err = model.First(&where, &modelOld)
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	err = tool.Gdb.Table("za_admin").Where("id = ?", models.Id).Updates(map[string]any{"real_name": models.RealName, "tel": models.Tel}).Error
	if err != nil {
		log.Println(err)
		controller.ResFail(c, "操作失败")
		return
	}
	model.AdminLog(1, "更新用户:"+modelOld.Name, c)
	controller.ResSuccessMsg(c)
}

// Create
//
//	@Summary	创建  使用headers头： Content-Type:application/json   使用raw json方式发送请求体
//	@Tags		后台-管理员
//	@Produce	json
//	@param		name		query		int	false	"账号名"
//	@param		real_name	query		int	false	"用户真实名称"
//	@param		pwd			query		int	false	"密码密文 md5(密码+_KW)"
//	@param		tel			query		int	false	"联系方式"
//	@param		switch		query		int	false	"账号开关 2:关闭 1:开启"
//	@param		type		query		int	false	"管理员类型 1 部门主管 2普通员工"
//	@param		role_id		query		int	false	"所属角色"
//	@Success	200			{string}	json{"code","message"}
//	@Router		/admin/admins/create [POST]
func (Admins) Create(c *gin.Context) {
	models := model.Admin{}
	err := c.Bind(&models)
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}

	modelOld := model.Admin{}
	tool.Gdb.Table("za_admin").Where("name = ?", models.Name).First(&modelOld)
	if modelOld.Name != "" {
		c.JSON(200, gin.H{
			"code": 2,
			"msg":  "此用户名已存在，请勿重复！",
		})
		return
	}

	models.Salt = fmt.Sprintf("%06d", rand.Int31())

	role := model.Role{}
	err = tool.Gdb.Table("za_role").Where("id = ?", models.RoleId).First(&role).Error
	if err != nil {
		log.Println(err)
		controller.ResFail(c, "请给用户分配角色！")
		return
	}
	models.GameId = models.RoleId
	models.RoleName = role.Name
	//kw := "_KW"
	//models.Pwd = tool.Md5string(tool.Md5string(models.Pwd+kw) + models.Salt)
	models.Pwd = tool.Md5string(models.Pwd + models.Salt)
	err = model.Create(&models)
	if err != nil {
		log.Println(err)
		controller.ResFail(c, "操作失败")
		return
	}
	model.AdminLog(1, "创建用户:"+models.Name, c)
	controller.ResSuccess(c, gin.H{"id": models.Id})
}

// Delete
//
//	@Summary	删除数据
//	@Tags		后台-管理员
//	@param		ids	formData	int	false	"ids"
//	@Success	200	{string}	json{"code","message"}
//	@Router		/admin/admins/delete [POST]
func (Admins) Delete(c *gin.Context) {
	var ids []int
	err := c.Bind(&ids)
	if err != nil || len(ids) == 0 {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	admin1 := model.Admin{}
	err = admin1.Delete(ids)
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	model.AdminLog(1, "删除用户:"+fmt.Sprintf("%v", ids), c)
	controller.ResSuccessMsg(c)
}

// AdminsRoleIDList
//
//	@Summary	获取用户下的角色ID列表
//	@Tags		后台-管理员
//	@param		adminsid	query		int		false	"管理员id"
//	@param		limit		query		int		false	"每页多少条"
//	@param		sort		query		string	false	"排序"
//	@param		key			query		string	false	"搜索条件"
//	@param		status		query		string	false	"状态(1:正常 2:禁用)"
//	@Success	200			{string}	json{"code","message","data"}
//	@Router		/admin/admins/adminsroleidlist [GET]
func (Admins) AdminsRoleIDList(c *gin.Context) {

	adminsid := controller.GetQueryToInt(c, "adminsid")
	roleList := []uint64{}
	where := model.Admin{Id: adminsid}
	err := model.PluckList(&model.Admin{}, &where, &roleList, "role_id")
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	controller.ResSuccess(c, &roleList)
}

// SetRole
//
//	@Summary	分配用户角色权限
//	@Tags		后台-管理员
//	@param		adminsid	query		int	false	"管理员id"
//	@Success	200			{string}	json{"code","message","data"}
//	@Router		/admin/admins/setrole [POST]
func (Admins) SetRole(c *gin.Context) {
	adminsid := controller.GetQueryToInt(c, "adminsid")
	var roleids []int
	err := c.Bind(&roleids)
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	ar := model.Admin{}
	err = ar.SetAdminRole(adminsid, roleids)
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	go model.CsbinAddRoleForUser(adminsid)
	controller.ResSuccessMsg(c)
}

// AdminList
//
//	@Summary	拉取所有的业务员或技术员等
//	@Tags		后台-管理员
//	@param		game_id	query		string	false	"1业务员 2财务员 3采购员 4仓库员 5曹总 6技术员 0所有"
//	@Success	200		{string}	json{"code","message","data"}
//	@Router		/admin/admins/adminlist [GET]
func (Admins) AdminList(c *gin.Context) {
	gameId := controller.GetQueryToInt(c, "game_id")
	var whereOrder []model.PageWhereOrder
	order := "ID DESC"
	whereOrder = append(whereOrder, model.PageWhereOrder{Order: order})

	var arr []interface{}
	arr = append(arr, 1)
	whereOrder = append(whereOrder, model.PageWhereOrder{Where: "switch = ?", Value: arr})

	if gameId > 0 {
		var arr1 []interface{}
		arr1 = append(arr1, gameId)
		whereOrder = append(whereOrder, model.PageWhereOrder{Where: "game_id = ?", Value: arr1})
	}

	type AdminWith struct {
		Id       int
		RealName string
		Tel      string
	}

	var list []AdminWith
	var total int64

	dbDB := tool.Gdb.Table("za_admin").
		Select("id,real_name,tel")

	if len(whereOrder) > 0 {
		for _, wo := range whereOrder {
			if wo.Order != "" {
				dbDB = dbDB.Order(wo.Order)
			}
			if wo.Where != "" {
				dbDB = dbDB.Where(wo.Where, wo.Value...)
			}
		}
	}

	err := dbDB.Find(&list).Error

	dbDB.Count(&total)

	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}

	controller.ResSuccessPage(c, total, &list)
}

// UserList
//
//	@Summary	拉取所有的业务员信息及旗下项目审核通过数和已完结数等
//	@Tags		审核功能
//	@param		key		query		string	false	"搜索条件"
//	@Success	200		{string}	json{"code","message","data"}
//	@Router		/admin/admins/userList [GET]
func (Admins) UserList(c *gin.Context) {

	key := controller.GetPageKey(c)

	type UserOrderStats struct {
		Id                    int
		RealName              string
		GameId                int
		Name                  string
		Tel                   string
		PendingCompletedCount int64
		Count                 int64
		CompletedOrderCount   int64
		PendingOrderCount     int64
	}

	// 查询所有用户的名称
	var users []struct {
		Id       int
		RealName string
		GameId   int
		Name     string
		Tel      string
	}

	var whereOrder []model.PageWhereOrder

	if key != "" {
		v := "%" + key + "%"
		var arr []interface{}
		arr = append(arr, v)
		arr = append(arr, v)
		//模糊搜素order_no或project_name
		whereOrder = append(whereOrder, model.PageWhereOrder{Where: "real_name like ? or tel like ?", Value: arr})
	}

	dbs := tool.Gdb.Table("za_admin").Where("game_id = 1")

	if len(whereOrder) > 0 {
		for _, wo := range whereOrder {
			if wo.Order != "" {
				dbs = dbs.Order(wo.Order)
			}
			if wo.Where != "" {
				dbs = dbs.Where(wo.Where, wo.Value...)
			}
		}
	}

	dbs.Pluck("id,real_name,game_id,name,tel", &users)

	// 为每个用户计算订单统计信息
	stats := make([]UserOrderStats, len(users))
	for i, user := range users {
		stats[i] = UserOrderStats{Id: user.Id, RealName: user.RealName, GameId: user.GameId, Name: user.Name, Tel: user.Tel}

		var aCount int64
		var cCount int64
		var pCount int64
		var poCount int64
		var count int64

		// 查询已批准、待审核和被拒绝的订单数
		tool.Gdb.Table("za_order").
			Where("duty = ?", user.Id)

		tool.Gdb.Table("za_order").
			Where("duty = ?", user.Id).Where("status <> 0").Where("status <> 2").Count(&count)

		tool.Gdb.Table("za_order").
			Where("duty = ?", user.Id).Where("status = 1").Count(&aCount)

		tool.Gdb.Table("za_order").
			Where("duty = ?", user.Id).Where("status = 3").Count(&poCount)

		tool.Gdb.Table("za_order").
			Where("duty = ?", user.Id).Where("status = 4").Count(&cCount)

		tool.Gdb.Table("za_order").
			Where("duty = ?", user.Id).Where("status = 5").Count(&pCount)

		stats[i].PendingCompletedCount = aCount + pCount
		stats[i].CompletedOrderCount = cCount
		stats[i].PendingOrderCount = poCount
		stats[i].Count = count

	}

	// 返回统计信息
	controller.ResSuccess(c, stats)

}

// Status
//
//	@Summary	更新  使用headers头： Content-Type:application/json   使用raw json方式发送请求体
//	@Tags		后台-管理员
//	@Produce	json
//	@param		id			formData		int	false	"id"
//	@param		switch		formData		int	false	"账号开关 2:关闭 1:开启"
//	@Success	200			{string}	json{"code","message"}
//	@Router		/admin/admins/status [POST]
func (Admins) Status(c *gin.Context) {
	type Admin struct {
		Id     int `json:"id" form:"id"`
		Switch int `json:"switch" form:"switch"`
	}
	models := Admin{}
	err := c.Bind(&models)
	fmt.Println(models)
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	where := model.Admin{}
	where.Id = models.Id
	modelOld := model.Admin{}
	_, err = model.First(&where, &modelOld)
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	err = tool.Gdb.Table("za_admin").Where("id = ?", models.Id).Updates(map[string]any{"switch": models.Switch}).Error
	if err != nil {
		log.Println(err)
		controller.ResFail(c, "操作失败")
		return
	}
	model.AdminLog(1, "开启或禁用用户:"+modelOld.Name, c)
	controller.ResSuccessMsg(c)
}
